<template>
  <div class="container">
    <div class="product">
      <NImage class="img" :src="product?.ImgUrl" alt="" srcset="" />
      <article class="content">
        <header>
          <h2>{{ product?.Name }}</h2>
        </header>
        <p class="description">{{ product?.Description }}</p>
        <p class="description">库存： {{ product?.Number }}</p>
        <p class="price">
          ￥<span>{{ product?.Price }}</span>
        </p>
        <p>选择数量:</p>
        <NInputNumber class="number" v-model:value="number" :min="1" />
        <NButton @click="addToCart" type="warning" size="large"
          >加入购物车</NButton
        >
      </article>
    </div>
    <div class="more">
      <NTabs type="line" animated>
        <NTabPane name="详情" tab="详情">
          <div class="detail img" v-html="product?.Detail"></div>
        </NTabPane>
      </NTabs>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  NImage,
  NInputNumber,
  NButton,
  NTabs,
  NTabPane,
  useMessage,
} from "naive-ui";
import { ref } from "vue";

import { useUserStore } from "@/stores/user";
import { useProduct } from "@/hooks/Product";
import { useOrderItem } from "@/hooks/OrderItem";

const props = defineProps<{
  id: string;
}>();

const message = useMessage();
const user = useUserStore();

const number = ref(1);
const { product, getProductByID } = useProduct();
const { addOrderItem } = useOrderItem();

async function addToCart() {
  if (user.user == null) {
    message.warning("请先进行登录!");
  }
  if (user.currentOrder == null) {
    await user.getCurrentOrder();
  }
  const msg = await addOrderItem({
    productID: product.value.ID,
    price: product.value.Price,
    orderID: user.currentOrder.ID,
    number: number.value,
  });
  await user.getCurrentOrderItems();
  message.success(msg);
}

(async () => {
  await getProductByID(props.id);
})();
</script>

<style lang="less" scoped>
.container {
  margin: 0 1em;

  .product {
    padding: 2em;
    background-color: white;
    border: 1px solid var(--border-color);
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 2em;

    .img {
      display: block;
      max-width: 400px;
      overflow: hidden;
    }

    .content {
      font-size: 1.1rem;
      max-width: 400px;

      > * + * {
        margin-top: 1em;
      }

      .description {
        max-height: 60px;
        text-overflow: ellipsis;
        overflow: hidden;
      }

      .price {
        color: red;

        span {
          font-size: 2em;
        }
      }

      .number {
        width: 14rem;
      }
    }
  }

  .more {
    margin-top: 1em;
    padding: 2em;
    background-color: white;
    border: 1px solid var(--border-color);
  }
}
</style>
